package com.example.myapplication;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

import com.example.myapplication.utils.MediaUtils;
import com.example.myapplication.vo.Mp3Info;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 音乐播放的服务
 */
public class PlayService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

    private MediaPlayer mplayer ;
    private int currentPostion;//当前正在播放的位置
    private ArrayList<Mp3Info> mp3Infos ;
    private MusicUpdateListener musicUpdateListener;
    private ExecutorService es = Executors.newSingleThreadExecutor();//创建线程池
    private boolean isPause = true;
    public static final int ORDER_PLAY = 1;//顺序播放
    public static final int RANDOM_PLAY = 2;//随机播放
    public static final int SINGLE_PLAY = 3;//单曲循环
    private int play_modle = ORDER_PLAY;//播放模式
    private SharedPreferences sharedPreferences;


    /**
     * 获取播放模式的方法
     * @return
     */
    public int getPlay_modle() {
        return play_modle;
    }

    /**
     * 设置播放模式的方法
     */
    public void setPlay_modle(int play_modle) {
        this.play_modle = play_modle;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("model",play_modle);
        editor.commit();

    }




    public PlayService() {
    }

    public boolean isPause(){
        return isPause;
    }

    public boolean isPlaying(){
        if (mplayer != null&&mplayer.isPlaying()){
                return true;
        }
        return false;
    }

    /**
     * 不断更新进度条的线程
     *
     */
    Runnable upDateRun = new Runnable() {
        @Override
        public void run() {
            while (true){
                if (musicUpdateListener != null&&mplayer!=null&&mplayer.isPlaying()){
                    musicUpdateListener.onPublish(getCurrentProgress());
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 监听播放事件的接口
     * @param mediaPlayer
     */
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Random random = new Random();
        switch (play_modle){
            case ORDER_PLAY:
                next();
                break;
            case RANDOM_PLAY:
                play(random.nextInt(mp3Infos.size()));
                break;
            case SINGLE_PLAY:
                play(currentPostion);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        mediaPlayer.reset();
        return false;
    }

    public class PlayBinder extends Binder {

        public PlayService getPlayService(){
            return PlayService.this;
        }

    }

    /**
     *
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
//        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return new PlayBinder();

    }

    @Override
    public void onCreate() {
        super.onCreate();
        mplayer = new MediaPlayer();
        mp3Infos = MediaUtils.getMp3Infos(this);
        es.execute(upDateRun);//开启更新进度的线程
        sharedPreferences = this.getSharedPreferences("setting",MODE_PRIVATE);
        currentPostion = sharedPreferences.getInt("curr",0);
        play_modle = sharedPreferences.getInt("model",1);
    }

    /**
     * 启动线程就得销毁
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (es!=null&&!es.isShutdown()){
            es.shutdown();
            es=null;
        }
    }

    /**播放
     * 如果位置大于零并小于播放列表
     * 就通过播放列表位置获取当前歌曲并开始播放
     * @param postion
     */
    public void play(int postion){
        mplayer.setOnCompletionListener(this);//注册播放完成监听事件
        mplayer.setOnErrorListener(this);
        if (postion>=0 && postion<mp3Infos.size()){
            Mp3Info mp3Info = mp3Infos.get(postion);
            try {
                mplayer.reset();
                mplayer.setDataSource(this, Uri.parse(mp3Info.getUrl()));
                mplayer.prepare();
                mplayer.start();
                currentPostion = postion;
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (musicUpdateListener != null){
                        musicUpdateListener.onChange(currentPostion);
            }
        }
        isPause = false;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("curr",currentPostion);
        editor.commit();
    }

    /**暂停
     * 如果正在播放，就暂停播放
     */
    public void pause(){
        if (mplayer.isPlaying()){
            mplayer.pause();
        }
        isPause = true;
    }

    /**下一首
     *如果当前歌曲位置是最后一首就接着播放第一首
     * 如果不是就直接播放下一首
     */
    public void next(){
        if (currentPostion+1 >= mp3Infos.size()-1){
            currentPostion=0;
        }else {
            currentPostion++;
        }
        play(currentPostion);
        isPause = false;
    }

    /**上一首
     * 如果当前是第一首就播放最后一首
     * 如果不是第一首，就正常播放上一首
     */
    public void prev(){
        if (currentPostion-1 < 0 ){
            currentPostion = mp3Infos.size()-1;
        }else {
            currentPostion--;
        }
        play(currentPostion);
        isPause = false;
    }

    /**
     * 如果音乐不等于空并且没有正在播放，就接着开始播放
     */
    public void start(){
        if (mplayer != null && !mplayer.isPlaying()){
            mplayer.start();
        }
        isPause = false;
    }

    /**
     * 更新状态的接口
     */
    public interface MusicUpdateListener{
         void onPublish(int progress);//进度条
         void onChange(int position);//切换歌曲位置
    }

    /**
     * 设置更新状态
     * @param musicUpdateListener
     */
    public void setMusicUpdateListener(MusicUpdateListener musicUpdateListener) {
        this.musicUpdateListener = musicUpdateListener;
    }

    /**
     * 跳转播放
     */

    public void seekTo(int mswc){
        mplayer.seekTo(mswc);
    }
    /**
     *获取播放列表的位置
     */
    public int getCurrentPostion() {
        if (mplayer != null ){
            return this.currentPostion;
        }
        return 0;
    }

    /**获取当前进度
     *如果有音乐并且正在播放，就获得当前位置
     */
    public int getCurrentProgress(){
        if (mplayer != null ){
            return mplayer.getCurrentPosition();
        }
        return 0;
    }
}
